const http = require('http')
const mysql = require('mysql')
const jwt = require('jsonwebtoken')

// 如何生成token
// jwt.sign(要转换的内容, key, 配置项)
// let token = jwt.sign({ name: "张三", age: 20 }, 'Wang', {
//     expiresIn: '1h'
// })
// console.log(token)

let con = mysql.createPool({
    user: 'root',
    password: 'root',
    host: 'localhost',
    database: '1_crud'
})


http.createServer((req, res) => {
    res.writeHead(200, {
        "Content-Type": "text/html;charset=utf-8"
    })


    // 定义请求方法
    if (req.method === "POST") {
        let post = ''
        // console.log(req.url)
        // 获取post方式传参

        req.on('data', (thunk) => {
            post += thunk
        })
        // 传输完毕
        req.on('end', () => {
            // 读取post请求传递的参数
            const { userName, passWord } = JSON.parse(JSON.parse(JSON.stringify(post)))
            // 1. 在数据库查询是否有该账号密码
            con.query(`select * from user where (name='${userName}') and (password='${passWord}')`, (err, data) => {
                if (data.length > 0) {
                    // 生成token
                    let token = jwt.sign({ userName, passWord }, 'Wang', {
                        expiresIn: '1h'
                    })
                    res.end(JSON.stringify({
                        code: 1,
                        msg: "登录成功",
                        token
                    }))
                } else {
                    // 账号密码错误
                    res.end(JSON.stringify({
                        code: -1,
                        msg: "请先去注册"
                    }))
                }
            })
        })

    } else {
        if (req.url === "/list") {
            console.log(req.headers)
            // 获取token信息
            const token = req.headers.authorization
            // 解析token
            // jwt.verify(token, )
            jwt.verify(token, 'Wang', (err, data) => {
                // 如果解析不成功
                if (err) {
                    res.end(JSON.stringify({
                        code: -1,
                        msg: "请先登录"
                    }))
                } else {
                    con.query(`select * from list`, (err, data) => {
                        res.end(JSON.stringify({
                            code: 1,
                            data,
                            msg: "数据获取成功"
                        }))
                    })
                }
            })

        }
    }
}).listen(3000)